<!doctype html>
<%@page import="com.macrosolution.exdebito.Role"%>
<html>
	<head>
		
		<meta name="layout" content="kickstart"/>
	<title>Mr-Rights|Gestione Utenti</title>
	</head>
<body>
<!-- RIBBON Macro Categori-->
			<div id="ribbon">
				<ol class="breadcrumb">
					<li>Credenziali</li><li>Utenti</li>
				</ol>
			</div>
			<!-- END RIBBON -->
			
			<!-- MAIN CONTENT -->
			<div id="content">
			<div class="row">
				<div class="col-lg-6">
					<div class="tree smart-form" id="tree_roles">
						
					</div>				
				</div>
				<div class="col-lg-6 " id="manage_users_section">
				
				
						
				</div>
				</div>
			</div>
<script src="${resource(dir: 'site/js/plugin/datatables', file: 'jquery.dataTables.min.js')}"></script>
<script src="${resource(dir: 'site/js/plugin/datatables', file: 'dataTables.colVis.min.js')}"></script>			
<script src="${resource(dir: 'site/js/plugin/datatables', file: 'dataTables.tableTools.min.js')}"></script>
<script src="${resource(dir: 'site/js/plugin/datatables', file: 'dataTables.bootstrap.min.js')}"></script>
<script src="${resource(dir: 'site/js/plugin/datatable-responsive', file: 'datatables.responsive.min.js')}"></script>
<script type="text/javascript">
		
		// DO NOT REMOVE : GLOBAL FUNCTIONS!
		var priority=0;
		$(document).ready(function() {
			
			pageSetUp();

			buildRolesTree();
			
	
		});
	
	function buildInnerTree(data,textStatus){
				var result='';
				var obj = data[0];
				if(obj.label!='CLIENTE'){
			    if(priority<obj.priority){
			    	priority=obj.priority;
				 	result+='<ul><li><span ><i class="fa fa-lg fa-user"></i>&nbsp;'+obj.label+'&nbsp;&nbsp;'+((obj.isReadOnly)?'[solo lettura]&nbsp;&nbsp;':'')+'<button type="button" class="btn btn-primary btn-sm" id="add_role" onclick="showUserRole('+obj.id+');"><i class="fa fa-lg fa-arrow-circle-right"></i></button></span>';
				 	if(data[1] && obj.priority<data[1].priority){
				 		data.splice(0, 1);
				 		result+=buildInnerTree(data,textStatus)+'</li></ul>';
					 	}else if(data[(1)] && obj.priority==data[(1)].priority){
					 		data.splice(0, 1);
					 		result+='</li>'+buildInnerTree(data,textStatus)+'</ul>';	
						 	}else if(!data[(1)]){
						 		result+='</li></ul>';
							 	}    
				 }else if(priority==obj.priority){
					 if(data[1] && obj.priority<data[1].priority){
						 data.splice(0, 1);
						 result+='<li><span ><i class="fa fa-lg fa-user"></i>&nbsp;'+obj.label+'&nbsp;&nbsp;'+((obj.isReadOnly)?'[solo lettura]&nbsp;&nbsp;':'')+'<button type="button" class="btn btn-primary btn-sm" id="add_role" onclick="showUserRole('+obj.id+');"><i class="fa fa-lg fa-arrow-circle-right"></i></button></span></li></ul>'+buildInnerTree(data,textStatus);	 
					 }
					 if(data[1] && obj.priority==data[1].priority){
						 data.splice(0, 1);
						 result+='<li><span ><i class="fa fa-lg fa-user"></i>&nbsp;'+obj.label+'&nbsp;&nbsp;'+((obj.isReadOnly)?'[solo lettura]&nbsp;&nbsp;':'')+'<button type="button" class="btn btn-primary btn-sm" id="add_role" onclick="showUserRole('+obj.id+');"><i class="fa fa-lg fa-arrow-circle-right"></i></button></span></li>'+buildInnerTree(data,textStatus);	 
					 }
					  

				 }
				}

			return result;
		}
		
	function buildTree(data,textStatus){
		var result=buildInnerTree(data,textStatus);
		$('#tree_roles').html(result); 
		$('.tree > ul').attr('role', 'tree').find('ul').attr('role', 'group');
		$('.tree').find('li:has(ul)').addClass('parent_li').attr('role', 'treeitem').find(' > span').attr('title', 'Collapse this branch').on('click', function(e) {
			var children = $(this).parent('li.parent_li').find(' > ul > li');
			if (children.is(':visible')) {
				children.hide('fast');
				$(this).attr('title', 'Expand this branch').find(' > i').removeClass().addClass('fa fa-lg fa-plus-circle');
			} else {
				children.show('fast');
				$(this).attr('title', 'Collapse this branch').find(' > i').removeClass().addClass('fa fa-lg fa-minus-circle');
			}
			e.stopPropagation();
		});		
		}
	
	function buildRolesTree(){
		 ${remoteFunction(asynchronous: true,
 					action:'get_roles',
					controller:'role',
					onSuccess:'buildTree(data,textStatus);'
					)} 
				
		}	
	function showUserRole(id_role){
		 	${remoteFunction(asynchronous: true,
					action:'get_users_role',
					controller:'user',
					params:'\'role=\'+id_role',
					update:'manage_users_section',
					onSuccess:'buildTable()'
					)} 
		}
	function showCancelAlert(id_user){
		$.SmartMessageBox({
			title : "<div class='row'><div class='col-md-2'><i class='fa '></i></div><div class='col-md-10'>Stai per eliminare un utente della piattaforma!</div>",
			content : "<div class='col-md-2'></div><div class='col-md-10'> Sei sicuro di volerlo fare?<BR/><BR/></div></div>",
			buttons:"[Si],[No]",
			sound:false
		}, function(ButtonPressed, Value) {
			if (ButtonPressed === "No") {
				
			}
			if (ButtonPressed === "Si") {
				${remoteFunction(asynchronous: true,
	 					action:'delete',
						controller:'user',
						params:'\'id=\'+id_user',
						update:'manage_users_section',
						onSuccess:'buildTable()'
						)} 
			}
			});
	}
	function addUser(){	
		${remoteFunction(asynchronous: true,
				action:'edit',
				controller:'user',
				update:'manage_users_section',
				onSuccess:'buildAddUser()'
				)}
		}

	function showAge(data,textStatus){
		$('#age').val(data);
		}

	function validateAddUser(){
		var $valid = $("#add_user_form").valid();
		if (!$valid) {
	        
	        throw new Error('step is invalid');
		}
		}
	function buildAddUser(){

			remappingBean();
		}

	function showEditUser(id_user,id_role){
		${remoteFunction(asynchronous: true,
					action:'edit',
					controller:'user',
					params:"'id='+id_user+'&id_role='+id_role",
					update:'manage_users_section',
					onSuccess:'buildAddUser()'
					)}
		
	}
	
	function buildTable(){
		/* BASIC ;*/
		var responsiveHelper_dt_basic = undefined;
		var responsiveHelper_datatable_fixed_column = undefined;
		var responsiveHelper_datatable_col_reorder = undefined;
		var responsiveHelper_datatable_tabletools = undefined;
		
		var breakpointDefinition = {
			tablet : 1024,
			phone : 480
		};

		$('#dt_basic').dataTable({
			"sDom": "<'dt-toolbar'<'col-xs-12 col-sm-6'f><'col-sm-6 col-xs-12 hidden-xs'l>r>"+
				"t"+
				"<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>",
			"autoWidth" : true,
			"preDrawCallback" : function() {
				// Initialize the responsive datatables helper once.
				if (!responsiveHelper_dt_basic) {
					responsiveHelper_dt_basic = new ResponsiveDatatablesHelper($('#dt_basic'), breakpointDefinition);
				}
			},
			"rowCallback" : function(nRow) {
				responsiveHelper_dt_basic.createExpandIcon(nRow);
			},
			"drawCallback" : function(oSettings) {
				responsiveHelper_dt_basic.respond();
			}
		});

	/* END BASIC */
	
	/* COLUMN FILTER  */
    var otable = $('#datatable_fixed_column').DataTable({
    	//"bFilter": false,
    	//"bInfo": false,
    	//"bLengthChange": false
    	//"bAutoWidth": false,
    	//"bPaginate": false,
    	//"bStateSave": true // saves sort state using localStorage
		"sDom": "<'dt-toolbar'<'col-xs-12 col-sm-6 hidden-xs'f><'col-sm-6 col-xs-12 hidden-xs'<'toolbar'>>r>"+
				"t"+
				"<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>",
		"autoWidth" : true,
		"preDrawCallback" : function() {
			// Initialize the responsive datatables helper once.
			if (!responsiveHelper_datatable_fixed_column) {
				responsiveHelper_datatable_fixed_column = new ResponsiveDatatablesHelper($('#datatable_fixed_column'), breakpointDefinition);
			}
		},
		"rowCallback" : function(nRow) {
			responsiveHelper_datatable_fixed_column.createExpandIcon(nRow);
		},
		"drawCallback" : function(oSettings) {
			responsiveHelper_datatable_fixed_column.respond();
		}		
	
    });
    
    // custom toolbar
    $("div.toolbar").html('<div class="text-right"><img src="img/logo.png" alt="SmartAdmin" style="width: 111px; margin-top: 3px; margin-right: 10px;"></div>');
    	   
    // Apply the filter
    $("#datatable_fixed_column thead th input[type=text]").on( 'keyup change', function () {
    	
        otable
            .column( $(this).parent().index()+':visible' )
            .search( this.value )
            .draw();
            
    } );
    /* END COLUMN FILTER */   

	/* COLUMN SHOW - HIDE */
	$('#datatable_col_reorder').dataTable({
		"sDom": "<'dt-toolbar'<'col-xs-12 col-sm-6'f><'col-sm-6 col-xs-6 hidden-xs'C>r>"+
				"t"+
				"<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-sm-6 col-xs-12'p>>",
		"autoWidth" : true,
		"preDrawCallback" : function() {
			// Initialize the responsive datatables helper once.
			if (!responsiveHelper_datatable_col_reorder) {
				responsiveHelper_datatable_col_reorder = new ResponsiveDatatablesHelper($('#datatable_col_reorder'), breakpointDefinition);
			}
		},
		"rowCallback" : function(nRow) {
			responsiveHelper_datatable_col_reorder.createExpandIcon(nRow);
		},
		"drawCallback" : function(oSettings) {
			responsiveHelper_datatable_col_reorder.respond();
		}			
	});
	
	/* END COLUMN SHOW - HIDE */

	/* TABLETOOLS */
	$('#datatable_tabletools').dataTable({
		
		// Tabletools options: 
		//   https://datatables.net/extensions/tabletools/button_options
		"sDom": "<'dt-toolbar'<'col-xs-12 col-sm-6'f><'col-sm-6 col-xs-6 hidden-xs'T>r>"+
				"t"+
				"<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-sm-6 col-xs-12'p>>",
        "oTableTools": {
        	 "aButtons": [
             "copy",
             "csv",
             "xls",
                {
                    "sExtends": "pdf",
                    "sTitle": "SmartAdmin_PDF",
                    "sPdfMessage": "SmartAdmin PDF Export",
                    "sPdfSize": "letter"
                },
             	{
                	"sExtends": "print",
                	"sMessage": "Generated by SmartAdmin <i>(press Esc to close)</i>"
            	}
             ],
            "sSwfPath": "js/plugin/datatables/swf/copy_csv_xls_pdf.swf"
        },
		"autoWidth" : true,
		"preDrawCallback" : function() {
			// Initialize the responsive datatables helper once.
			if (!responsiveHelper_datatable_tabletools) {
				responsiveHelper_datatable_tabletools = new ResponsiveDatatablesHelper($('#datatable_tabletools'), breakpointDefinition);
			}
		},
		"rowCallback" : function(nRow) {
			responsiveHelper_datatable_tabletools.createExpandIcon(nRow);
		},
		"drawCallback" : function(oSettings) {
			responsiveHelper_datatable_tabletools.respond();
		}
	});
	
		}

		</script>			
</body>

</HTML>			
